<template>
  <el-drawer
    title="预览"
    direction="rtl"
    :visible.sync="innerVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    size="80%"
    :append-to-body="false"
    :wrapper-closable="!loading"
    @close="closeDialog()"
  >
    <template slot="title">
      <el-row type="flex" align="center">
        <el-col :span="12">预览</el-col>
        <el-col :span="12" style="display: flex; justify-content: right">
          <el-date-picker
            v-model="comparisonDateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            style="margin-right: 10px"
            @change="comparisonDateRangeChange"
          />
          <el-button
            type="primary"
            icon="el-icon-download"
            :loading="loading"
            size="small"
            @click="downloadCharImage"
          >
            下载当前页图
          </el-button>
          <!--          <el-button-->
          <!--            type="primary"-->
          <!--            icon="el-icon-download"-->
          <!--            :loading="loading"-->
          <!--            size="small"-->
          <!--            @click="download"-->
          <!--          >-->
          <!--            下载PDF-->
          <!--          </el-button>-->
          <el-button
            icon="el-icon-close"
            size="small"
            :disabled="loading"
            @click="cancel"
          >
            关闭
          </el-button>
        </el-col>
      </el-row>
    </template>
    <div ref="container" class="wrapper">
      <div ref="textContainer" class="text-container">
        <div class="text-title fontBold">
          <div class="text-underline">管理动作</div>抽查成绩（<span style="font-weight: normal">检查日期：</span><span style="color: red">{{ checkDate }}</span>）
        </div>
        <div class="text-title fontBold" style="margin-bottom: 10px">
          {{ dataFormat.deptName }}-<div v-if="current.projectName" class="text-underline">{{ current.projectName }}</div>
        </div>
        <div class="text-content">
          <span class="fontBold">1、第一责任人（集群/事业部）：</span><span style="margin-right: 10px">{{ taskInfo.principalName || '/' }}</span>
          <span class="fontBold">2、项目总：</span><span style="margin-right: 10px">{{ taskInfo.xmzName || '/' }}</span>
          <span class="fontBold">3、项目经理：</span><span style="margin-right: 10px">{{ taskInfo.xmjlName || '/' }}</span>
          <span class="fontBold">4、施工单位：</span><span style="margin-right: 10px">{{ dataFormat.constructionName || '/' }}</span>
          <span class="fontBold">5、陪检专家：</span><span style="margin-right: 10px">{{ taskInfo.expertName || '/' }}</span>
        </div>
        <div class="text-content fontBold">
          6、检查成绩：{{ current.gldzScore }}分（<span :style="{ color: valueQualified(current.gldzLevel) ? '#00AF4D' : 'red'}">{{ levelLabelMap[current.gldzLevel] }}</span>）
        </div>
      </div>
      <div ref="groupActionChart" class="char-container" />
    </div>

  </el-drawer>
</template>

<script>
import * as echarts from 'echarts'
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
import {getGldzReportPreviewData} from '@/api/projectInspection/courseCheck'

export default {
  name: 'GldzReportPreview',
  components: {
  },
  filters: {
    typeName(val) {
      const typeMap = { civil: '土建', handcover: '精装' }
      return typeMap[val]
    },
    valueQualified(val) {
      return val !== 'C'
    }
  },
  props: {
  },
  data() {
    return {
      innerVisible: false,
      loading: false,
      rules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ]
      },
      checkShowFields: [],
      indexMap: {
        0: '①', 1: '②', 2: '③', 3: '④'
      },
      reportData: {},
      current: {},
      comparisonDateRange: [],
      pickerOptions: {},
      taskInfo: {},
      levelLabelMap: {
        A: '优秀', B: '合格', C: '不合格'
      }
    }
  },
  computed: {
    dataFormat() {
      const data = this.current
      const deptNames = []
      const clusterName = data.deptName1 || ''
      if (clusterName) {
        deptNames.push(clusterName.indexOf('集群') ? clusterName : clusterName + '集群')
      }
      const divisionName = data.deptName2 || ''
      if (divisionName) {
        deptNames.push(divisionName.indexOf('事业部') ? divisionName : divisionName + '事业部')
      }
      const cityCorporationName = data.deptName3 || ''
      if (cityCorporationName) {
        deptNames.push(cityCorporationName.indexOf('城市公司') ? cityCorporationName : cityCorporationName + '城市公司')
      }
      const constructionNames = (data.childList || []).map(item => item.constructionName)
      const constructionName = constructionNames.length === 0 ? data.constructionName : [...new Set(constructionNames)].join(',')
      return { deptName: deptNames.join('-'), constructionName: constructionName || '/' }
    },
    checkDate() {
      let result = '-'
      const checkDate = this.current.checkDate
      if (checkDate) {
        result = this.parseTime(checkDate, '{y}.{m}.{d}')
      }
      return result
    }
  },
  watch: {},
  created() {
  },
  methods: {
    async init(current) {
      this.innerVisible = true
      this.current = current
      const currentTime = new Date()
      let year = parseInt(this.parseTime(currentTime, '{y}'))
      if (currentTime.getTime() < new Date(`${year}-12-26`).getTime()) {
        year--
      }
      this.comparisonDateRange = [`${year}-12-26`, `${year + 1}-12-25`]
      this.checkShowFields = this.getCheckShowFields(current)
      await this.queryComparisonData(current, this.comparisonDateRange)
    },
    /**
     * 判断是否合格
     * @param val
     * @return {boolean}
     */
    valueQualified(val) {
      return val !== 'C'
    },
    /**
     * 对比时间改变
     * @param value
     */
    comparisonDateRangeChange(value) {
      this.queryComparisonData(this.current, value)
    },
    /**
     * 查询对比数据
     * @param current
     * @param comparisonDateRange
     * @return {Promise<void>}
     */
    async queryComparisonData(current, comparisonDateRange) {
      if (this.loading || comparisonDateRange.length !== 2) {
        return
      }
      this.loading = true
      await getGldzReportPreviewData({ id: current.gldzId, startDate: comparisonDateRange[0], endDate: comparisonDateRange[1] }).then(res => {
        const data = res && res.code === 200 ? res.data : {}
        this.taskInfo = data.info
        this.$nextTick(_ => {
          const echart = echarts.init(this.$refs.groupActionChart)
          const rowCounts = []
          const qualified = []
          const unQualified = []

          for (const item of data.data) {
            item.score = item.score <= 0 ? 0 : item.score
            if (item.qualified) {
              qualified.push(item)
            } else {
              unQualified.push(item)
            }
            const { value, rowCount } = this.xAxisLabelFormatter(item.projectName)
            item.projectName = value
            rowCounts.push(rowCount)
          }

          qualified.sort((a, b) => b.score - a.score)
          unQualified.sort((a, b) => b.score - a.score)
          const maxRows = Math.max.apply(null, rowCounts)
          const list = qualified.concat(unQualified)
          const constructionXAxis = []
          const constructionValues = []
          let minValue = 100
          list.forEach(item => {
            const value = item.score
            const valueItem = { value }
            if (current.gldzId === item.gldzId) {
              valueItem.itemStyle = { color: '#EE7D31' }
            }
            if (!item.qualified) {
              valueItem.label = { color: 'red' }
            }
            constructionXAxis.push(item.projectName)
            constructionValues.push(valueItem)
            if (value < minValue) {
              minValue = value
            }
          })
          const option = this.getOption('集团管理动作得分情况', constructionXAxis, constructionValues, maxRows * 12 + 10, minValue)
          echart.resize()
          echart.setOption(option)
        })
      }).catch(err => {
        console.log(err)
      }).finally(_ => {
        setTimeout(_ => {
          this.loading = false
        }, 250)
      })
    },
    /**
     * 获取chart配置
     * @param title
     * @param xAxis
     * @param values
     * @param bottom
     * @param minValue
     * @return {{yAxis: {min: number, max: number, type: string}, xAxis: {axisLabel: {interval: number, fontSize: number}, data: *[], axisTick: {show: boolean}, type: string}, grid: {left: number, bottom: number, right: number}, series: [{barWidth: string, barMaxWidth: string, data: *[], barMinWidth: string, itemStyle: {color: string}, label: {show: boolean, position: string}, type: string, markLine: {symbol: string[], silent: boolean, data: [{yAxis: number, lineStyle: {color: string}, name: string, label: {formatter: string, distance: number[], color: string, position: string}}]}}], textStyle: {fontFamily: string, color: string}, title: {left: string, text: string, textStyle: {fontFamily: string, color: string}}}}
     */
    getOption(title = '', xAxis = [], values = [], bottom = 0, minValue) {
      return {
        textStyle: {
          color: '#000',
          fontFamily: 'Simsun'
        },
        title: {
          text: title,
          left: 'center',
          textStyle: {
            color: '#000',
            fontFamily: 'Simsun'
          },
          subtext: '（注：红色数值标识为不合格）',
          subtextStyle: {
            color: 'red'
          }
        },
        grid: {
          top: 80,
          left: 30,
          right: 0,
          bottom: bottom
        },
        xAxis: {
          type: 'category',
          data: xAxis,
          axisLabel: {
            interval: 0,
            fontSize: 12
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          min: minValue > 70 ? 70 : parseInt((minValue / 10).toString()) * 10,
          max: 100
        },
        series: [{
          type: 'bar',
          label: {
            show: true,
            position: 'top'
          },
          itemStyle: {
            color: '#5B9CD6'
          },
          barWidth: '30%',
          barMaxWidth: '40%',
          barMinWidth: '20%',
          markLine: {
            silent: false,
            symbol: ['none', 'none'],
            data: [{
              name: '线',
              yAxis: 80,
              lineStyle: {
                color: '#00AF4D',
                width: 2
              },
              label: {
                distance: [0, 50],
                formatter: '合格：{c}',
                position: 'insideEndTop',
                color: '#00AF4D'
              }
            }]
          },
          data: values
        }]
      }
    },
    /**
     * X轴内容格式化
     * @param value
     * @return {string|{rowCount: number, value: string}}
     */
    xAxisLabelFormatter(value) {
      // const specialChars = value.match(/[^\u4e00-\u9fa5]/g)
      // const chars = []
      // if (specialChars && specialChars.length > 0 && specialChars[0] !== '、') {
      //   const specialStr = specialChars.join('')
      //   const strings = value.split(specialStr)
      //   chars.push(...strings[0].split(''))
      //   const specials = specialStr.split('、')
      //   specials.forEach((special, index) => {
      //     chars.push(special)
      //     if (index < specials.length - 1) {
      //       chars.push('、')
      //     }
      //   })
      //   if (strings[1]) {
      //     chars.push(...strings[1].split(''))
      //   }
      // } else {
      //   chars.push(...value.split(''))
      // }
      let chars = []
      const length = value.length
      if (length > 10) {
        const rows = Math.ceil(length / 10)
        for (let i = 0; i < length; i = i + rows) {
          chars.push(value.substring(i, i + rows))
        }
      } else {
        chars = value.split(/[\t\r\f\n\s]*/g)
      }
      return { value: chars.join('\n'), rowCount: chars.length }
    },
    /**
     * 关闭窗口
     */
    closeDialog() {
      this.innerVisible = false
    },
    /**
     * 取消操作
     */
    cancel() {
      this.closeDialog()
    },
    /**
     * 下载
     */
    async download() {
      this.loading = true
      const pdf = new JsPDF('l', 'pt', 'a4')
      try {
        html2canvas(this.$refs.container, {
          dpi: 300,
          // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
          // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
          useCORS: true
        }).then(canvas => {
          const contentWidth = canvas.width
          const contentHeight = canvas.height
          // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
          const imgWidth = 595.28 / contentHeight * contentWidth
          const imgHeight = 595.28
          const pageData = canvas.toDataURL('image/jpeg', 1.0)
          pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          pdf.save('飞检成绩.pdf')
        })
      } catch (e) {
        this.$message.error('下载失败')
      } finally {
        setTimeout(_ => {
          this.loading = false
        }, 250)
      }
    },
    /**
     * 下载
     */
    download1() {
      // this.loading = false
      // const contentWidth = canvas.width
      // const contentHeight = canvas.height
      //
      // // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      // const imgWidth = 595.28 / contentHeight * contentWidth
      // const imgHeight = 595.28
      //
      // const pageData = canvas.toDataURL('image/jpeg', 1.0)
      const pdf = new JsPDF('l', 'pt', 'a4')

      pdf.html(
        this.$refs.textContainer, { callback: dispose => { pdf.save('Test.pdf') } },
        dispose => {
          // dispose: object with X, Y of the last line add to the PDF
          //          this allow the insertion of new lines after html
          pdf.save('飞检成绩.pdf')
        })

      // pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
    },
    /**
     * 获取检查字段集合
     * @param data 项目检查数据
     * @return {*[]}
     */
    getCheckShowFields(data) {
      const result = []
      if (data.fslLevel) {
        result.push({ name: '防渗漏', value: data.fslLevel + '级', qualified: this.valueQualified(data.fslLevel) })
      }
      if (data.zlScore) {
        result.push({ name: '质量', value: data.zlScore + '分', qualified: this.valueQualified(data.zlLevel) })
      }
      if (data.aqScore) {
        result.push({ name: '安全生产', value: data.aqScore + '分', qualified: this.valueQualified(data.aqLevel) })
      }
      if (data.wmScore) {
        result.push({ name: '文明施工', value: data.wmScore + '分', qualified: this.valueQualified(data.wmLevel) })
      }
      return result
    },
    /**
     * 下载图表图片
     */
    downloadCharImage() {
      this.loading = true
      try {
        html2canvas(this.$refs.container, {
          dpi: 300,
          // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
          // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
          useCORS: true
        }).then(canvas => {
          const link = document.createElement('a')
          link.href = canvas.toDataURL()
          link.setAttribute('download', '管理动作抽查成绩.png')
          link.style.display = 'none'
          document.body.appendChild(link)
          link.click()
        }).catch(err => {
          throw err
        })
      } catch (e) {
        this.$message.error('生成图片异常，请刷新重试')
      } finally {
        setTimeout(_ => {
          this.loading = false
        }, 250)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  height: calc(100% - 10px);
  width: calc(100% - 20px);
  margin: 0 10px 10px;
  padding: 10px;
  font-family: Simsun;
  display: flex;
  flex-direction: column;
  .fontBold {
    font-weight: bold;
  }
  .text-container {
    color: black;
    .text-title {
      font-size: 26px;
      text-align: center
    }
    .text-content {
      font-size: 18px;
      margin: 5px 0;
    }
  }
  .char-container {
    flex: 1;
  }
  .text-underline {
    border-bottom: 2px solid black;
    padding-bottom: 1px;
    display:inline;
    text-decoration-color:rgba(151,151,151,.2);
  }
}

</style>
